package com.snail.file.service.impl;

import com.alibaba.nacos.common.utils.IoUtils;
import com.snail.file.config.FileConfigProperties;
import com.snail.file.property.MinioFile;
import com.snail.file.utils.FileUploadUtils;
import com.snail.system.api.domain.SysFile;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * Minio 文件存储
 *
 * @author snail
 */
@Service("minioSysFileService")
public class MinioSysFileServiceImpl {
    @Autowired
    private FileConfigProperties properties;

    @Autowired
    private MinioClient client;

    /**
     * Minio文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    public String uploadFile(MultipartFile file) throws Exception {
        String fileName = FileUploadUtils.extractFilename(file);
        InputStream inputStream = file.getInputStream();
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(properties.getMinio().getBucketName())
                .object(fileName)
                .stream(inputStream, file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        client.putObject(args);
        IoUtils.closeQuietly(inputStream);
        return fileName;
    }

    /**
     * 下载附件
     * @param file 附件信息
     * @return 结果
     */
    public InputStream download(SysFile file) throws Exception {
        MinioFile minio = properties.getMinio();
        GetObjectArgs args = GetObjectArgs.builder()
                .bucket(minio.getBucketName())
                .object(file.getFileUrl())
                .build();
        return client.getObject(args);
    }

    /**
     * 删除文件
     * @param file 文件信息
     */
    public void delete(SysFile file) throws Exception{
        MinioFile minio = properties.getMinio();
        RemoveObjectArgs args = RemoveObjectArgs.builder()
                .bucket(minio.getBucketName())
                .object(file.getFileUrl())
                .build();
        client.removeObject(args);
    }
}
